package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.One;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author zsk
 * @since 2022-04-11
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    /**
     * 登录验证
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //非空判断
        if (dto == null || dto.getName() == null || dto.getPassword() == null) {
            //返回结果
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据姓名查询数据库中数据
        //构建查询条件
        LambdaQueryWrapper<AdUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdUser::getName, dto.getName());

        //查询
        AdUser one = this.getOne(wrapper);
        if (one == null) {
            //返回结果
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String pwd = dto.getPassword();
        String newPwd = pwd + one.getSalt();

        //使用md5加密
        String pass = DigestUtils.md5DigestAsHex(newPwd.getBytes());

        //使用工具类比对
        if (pass.equals(one.getPassword())) {
            //一致,使用JWT生成token信息
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", one.getId());
            //生成token中存放用户id，方便后续操作
            String token = AppJwtUtil.getToken(userInfo);

            //返回前端信息
            Map<String, Object> map = new HashMap<>();
            //密码电话等信息不需要返回
            one.setPhone(null);
            one.setPassword(null);
            one.setEmail(null);
            one.setSalt(null);
            map.put("user", one);

            map.put("token", token);

            return ResponseResult.okResult(map);

        } else {
            //不一致,返回结果
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);

        }


    }
}
